<template>
  <div class="f_div" v-loading="loading">
    <div class="t_div">
      基础资料 / 客户 /客户管理 / <a href="#">{{ name }}</a>
    </div>
    <el-container>
      <el-header class="header">
        <div class="h_div">
          <div class="h_in_vid">基础信息</div>
        </div>
      </el-header>
      <el-main class="main">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
          status-icon>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户编码" prop="ct_numbering">
                <el-input v-model="ruleForm.ct_numbering" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="ct_cl_name">
                <el-input v-model="ruleForm.ct_cl_name" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属行业" prop="ct_lndustry">
                <el-input v-model="ruleForm.ct_lndustry" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户级别" prop="ct_level">
                <el-select v-model="ruleForm.ct_level" placeholder="请选择" :teleported="false">
                  <el-option v-for="item in options" :key="item.dict_code" :label="item.dict_label"
                    :value="item.dict_code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户标签" prop="ct_label">
                <el-select v-model="ruleForm.ct_label" placeholder="请选择" :teleported="false">
                  <el-option v-for="item in options2" :key="item.dict_code" :label="item.dict_label"
                    :value="item.dict_code" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="区域" prop="ct_region">
                <el-input v-model="ruleForm.ct_region" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="公司地址" prop="ct_address">
                <el-input v-model="ruleForm.ct_address" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="邮编" prop="ct_postcode">
                <el-input v-model="ruleForm.ct_postcode" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注信息" prop="ct_information">
                <el-input v-model="ruleForm.ct_information" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户状态">
                <el-switch v-model="ruleForm.ct_state" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-header class="header">
            <div class="h_div">
              <div class="h_in_vid">联系人信息</div>
            </div>
          </el-header>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名" prop="ct_name">
                <el-input v-model="ruleForm.ct_name" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="ct_phone">
                <el-input v-model="ruleForm.ct_phone" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="ct_department">
                <el-input v-model="ruleForm.ct_department" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="职位" prop="ct_posts">
                <el-input v-model="ruleForm.ct_posts" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="E-mail" prop="ct_email">
                <el-input v-model="ruleForm.ct_email" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="QQ" prop="ct_qq">
                <el-input v-model="ruleForm.ct_qq" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-header class="header">
            <div class="h_div">
              <div class="h_in_vid">财务信息</div>
            </div>
          </el-header>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="发票抬头" prop="ct_io_title">
                <el-input v-model="ruleForm.ct_io_title" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纳税人识别号" prop="ct_tp_identification">
                <el-input v-model="ruleForm.ct_tp_identification" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行" prop="ct_bank">
                <el-input v-model="ruleForm.ct_bank" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="开户名称" prop="ct_ao_name">
                <el-input v-model="ruleForm.ct_ao_name" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行账号" prop="ct_account">
                <el-input v-model="ruleForm.ct_account" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item>
                <el-button type="primary" style="width: 80px" @click="onSubmit">保存</el-button>
                <el-button style="width: 80px" @click="cancel">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { onMounted, reactive, ref, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getRandomString } from "@/randomString/random.js";
import axios from "axios";
import $http from '@/axios/base.js';

export default {
  name: "app",
  setup() {
    let ruleForm = reactive({
      ct_id: 0,
      ct_numbering: "",
      ct_cl_name: "",
      ct_lndustry: "",
      ct_level: "",
      ct_label: "",
      ct_region: "",
      ct_address: "",
      ct_postcode: "",
      ct_information: "",
      ct_state: true,
      ct_name: "",
      ct_phone: "",
      ct_department: "",
      ct_posts: "",
      ct_email: "",
      ct_qq: "",
      ct_io_title: "",
      ct_tp_identification: "",
      ct_bank: "",
      ct_ao_name: "",
      create_by: sessionStorage.getItem("empname"),
      create_time: new Date().toISOString().slice(0, 10).toString(),
      is_del: 0,
      update_by: "",
      update_time: "",
    });

    let router = useRouter();
    let route = useRoute();

    let name = ref();

    let rulelist = ref([
      {
        url: "",
      },
    ]);

    let rulelist2 = ref([
      {
        url: "",
      },
    ]);

    let loading = ref(false);

    let options = ref([]);

    let options2 = ref([]);

    let options3 = ref([]);

    let ruleFormRef = ref(null);
    let upload = ref(null);
    const dialogImageUrl = ref("");
    const dialogVisible = ref(false);
    const disabled = ref(false);

    const rules = reactive({
      ct_cl_name: [
        {
          required: true,
          message: "姓名不能为空",
          trigger: "blur",
        },
      ],
      ct_phone: [
        {
          required: true,
          message: "手机号码不能为空",
          trigger: "blur",
        },
        {
          pattern:
            /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
          message: "请输入正确的手机号码格式",
          trigger: "blur",
        },
      ],

    });

    function handleRemove(file) {
      console.log(file);
      const index = rulelist.value.indexOf(file);
      if (index !== -1) {
        rulelist.value.splice(index, 1);
      }
      const index2 = rulelist2.value.indexOf(file);
      if (index2 !== -1) {
        rulelist2.value.splice(index2, 1);
      }
    }

    function handlePictureCardPreview(file) {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    }

    function handleDownload(file) {
      var now = new Date();

      // 获取年、月、日、时、分、秒
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // 注意月份是从 0 开始的
      var day = now.getDate();
      var imageUrl = file.url;
      var link = document.createElement("a");
      link.href = imageUrl;
      link.download =
        "七尾-" + year + month + day + getRandomString(8) + ".jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    function handleExceed(files) {
      // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
      upload.value.clearFiles();
      const file = files[0]; // 获取最新的文件
      file.uid = Date.now(); // 为文件生成唯一的标识符
      upload.value.handleStart(file); // 开始上传最新的文件
      //upload.value.submit();
    }

    const handleUploadSuccess = (response, file, fileList) => {
      // 处理上传成功的逻辑，如显示成功消息或更新UI
      console.log("上传成功", response, file, fileList);
    };

    const handleUploadError = (error, file, fileList) => {
      // 处理上传失败的逻辑，如显示错误消息或更新UI
      console.error("上传失败", error, file, fileList);
    };

    function onSubmit() {

      ruleFormRef.value.validate((valid) => {
        if (valid) {
          //这里可以执行提交表单的操作，比如发送请求到后端
          console.log(ruleForm);
          if (ruleForm.ct_state == true) ruleForm.ct_state = "0";
          else ruleForm.ct_state = "1";
          if (ruleForm.ct_id == 0) {
            $http
              .post(`http://localhost:5261/api/Ct_/AddCt`, ruleForm)
              .then((res) => {
                if (res) {
                  ElMessage.success("添加成功！！！");
                  setTimeout(() => {
                    router.push("/Client");
                  }, 500);
                } else {
                  ElMessage.error("添加失败！！！");
                }
              })
              .catch((err) => console.log(err));
          } else {
            ruleForm.update_by = sessionStorage.getItem("empname");
            ruleForm.update_time = new Date()
              .toISOString()
              .slice(0, 10)
              .toString();
            if (ruleForm.ct_state == true) {
              ruleForm.ct_state = 0;
            } else {
              ruleForm.ct_state = 1;
            }
            $http
              .put("http://localhost:5261/api/Ct_/UpdCt", ruleForm)
              .then((res) => {
                ElMessage.success("修改成功！！！");
                setTimeout(() => {
                  router.push("/Client");
                }, 500);
              })
              .catch((err) => console.log(err));
          }
        } else {
          //验证没有通过
          ElMessage.warning("请填写完整数据！！！");
        }
      });
    }

    function show(id) {
      console.log(id);
      $http
        .get(`http://localhost:5261/api/Ct_/GetCustomer/${id}`).then((res) => {
          ruleForm.ct_id = res.ct_id;
          ruleForm.ct_numbering = res.ct_numbering;
          ruleForm.ct_cl_name = res.ct_cl_name;
          ruleForm.ct_lndustry = res.ct_lndustry;
          ruleForm.ct_level = res.ct_level;
          ruleForm.ct_label = res.ct_label;
          ruleForm.ct_region = res.ct_region;
          ruleForm.ct_address = res.ct_address;
          ruleForm.ct_postcode = res.ct_postcode;
          ruleForm.ct_information = res.ct_information;
          ruleForm.ct_name = res.ct_name;
          ruleForm.ct_phone = res.ct_phone;
          ruleForm.ct_department = res.ct_department;
          ruleForm.ct_posts = res.ct_posts;
          ruleForm.ct_email = res.ct_email;
          ruleForm.ct_qq = res.ct_qq;
          ruleForm.ct_io_title = res.ct_io_title;
          ruleForm.ct_tp_identification = res.ct_tp_identification;
          ruleForm.ct_bank = res.ct_bank;
          ruleForm.ct_ao_name = res.ct_ao_name;
          ruleForm.ct_account = res.ct_account;

          if (res.ct_state == 0) {
            ruleForm.ct_state = true;
          } else {
            ruleForm.ct_state = false;
          }
        })
        .catch((err) => console.log(err));
    }

    function showGender(value) {
      axios
        .get("http://localhost:5261/api/Sys_Dict_data/Get_Dict_Types", {
          params: {
            Dict_name: value,
          },
        })
        .then((res) => {
          if (value == "客户级别") options.value = res.data;
          if (value == "客户标签") options2.value = res.data;
        })
        .catch((err) => console.log(err));
    }

    function showCarrier() {
      axios
        .get("http://localhost:5261/api/Carrier_ment/Carrier_Ments")
        .then((res) => {
          options3.value = res.data;
        })
        .catch((err) => console.log(err));
    }

    function cancel() {
      router.push("/Client");
    }

    onMounted(() => {
      openFullScreen1();
      showGender("客户级别");
      showGender("客户标签");
      showCarrier();
      name.value = route.query.name;
      var id = route.query.id;
      if (id != 0) {
        show(id);
      } else {
        rulelist.value = [];
        rulelist2.value = [];
      }
    });

    const openFullScreen1 = () => {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    };

    return {
      loading,
      name,
      route,
      options,
      options2,
      options3,
      dialogImageUrl,
      dialogVisible,
      ruleForm,
      rules,
      ruleFormRef,
      rulelist,
      rulelist2,
      disabled,
      router,
      openFullScreen1,
      showCarrier,
      handleRemove,
      handlePictureCardPreview,
      handleDownload,
      handleExceed,
      handleUploadSuccess,
      handleUploadError,
      onSubmit,
      show,
      cancel,
      upload,
      showGender
    };
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 50px;
  background-color: #006eff;
}

.el-radio-group {
  margin-right: 12px;
}

.t_div {
  margin-bottom: 20px;
  text-align: left;
  font-size: 14px;
  color: #b3b4b6;
}

a {
  text-decoration: none;
}

.f_div {
  padding: 0px 50px;
}

.h_div {
  border-bottom: 1px solid #f2f2f2;
  height: 39px;
}

.h_in_vid {
  width: 100px;
  height: 20px;
  margin-top: 20px;
  border-left: 5px solid #006eff;
}

.header {
  background-color: #ffffff;
  border-radius: 10px 10px 0px 0px;
}

.main {
  background-color: #ffffff;
  border-radius: 0px 0px 10px 10px;
  height: 820px;
}

.form_content {
  margin-left: 50px;
}
</style>